"use strict";
const mvc = require("cosjs.mvc");
const moment = require("moment");

//检查活动日期
exports.check = async function (id) {

    let api = '/active/', data = { "id": id, "keys": ["s_type", "s_id"] };
    let ret = await mvc.library('spirit/gzone', api, data);
    if (arguments[1]) {
        return ret
    } else {
        return await mvc.library.call(this.updater, 'shop/filter', ret);
    }
}

//计算卡牌加成
exports.attr = function (corps = [], st) {

    return BrideWarHelper.cardActiveEffect(BrideWarHelper.defaultCard(st).concat(corps))

}

//战斗结算
exports.result = async function (id, battleData) {

    let win = battleData.win == this.updater.uid

    this.updater.daily.key('bw')
    await this.updater.data()
    let bw = this.updater.daily.get('bw')
    if (!bw) {
        return this.error('M7GLBR1', '跨天了')
    }

    bw.reward = bw.reward || []
    if (((!battleData.escape && battleData.tar == 4) || (battleData.tar < 4 && win)) && !bw.reward.includes(battleData.tar)) {
        let config = this.config('mStage', battleData.tar)
        this.updater.add(config.item)
        bw.reward.push(battleData.tar)
    }

    let active = await exports.check.call(this, bw.id)

    if (battleData.tar < 4 && win) {
        let ret = [parseInt(battleData.tar)]
        let ids = BrideWarHelper.defaultCard(active.STime).concat(bw.corps)
        while (ret.length < 4) {
            let id = Math.roll(1, 52)
            if (!ids.includes(id)) {
                ret.push(id)
                ids.push(id)
            }
        }
        bw.choice = ret
    } else if (battleData.tar == 4) {
        let p = battleData.player[0]
        bw.hurt += p.hurt
        if (p.hurt > bw.hh) {
            bw.hh = Math.max(p.hurt)
            await setBwSort.call(this, bw.id, this.updater.uid, bw.hh)
        }
    }

    this.updater.daily.set('bw', bw)

    return this.updater.save();
}

function setBwSort(id, uid, hurt) {

    let karr = [id, 'bw']
    karr.push(this.library("time/sign"));
    let kstr = karr.join('-');

    let redis = this.model.redis("sort", this.sid, kstr);
    redis.stamp();
    // redis.limit(100);
    return redis.set(uid, hurt);
}

function bwSort(id, offset = 0) {
    let karr = [id, 'bw']
    karr.push(this.library("time/sign", Date.now() + offset * 24 * 3600 * 1000));
    let kstr = karr.join('-');

    let redis = this.model.redis("sort", this.sid, kstr);

    redis.stamp();

    return redis;
    // redis.limit(100);
}

exports.sort = bwSort

const BrideWarHelper = {
    defaultCard(st) {
        // let active = mvc.config('mActive', 10008)
        // let d = moment().diff(active.STtime, 'days')
        let d = moment().diff(new Date(st), 'days')
        d = d % 52
        let id = d + 1
        let c = mvc.config('mBaseCard', id)
        return JSON.clone(c.card)
    },
    cardActiveEffect(corps) {

        let id = 0;
        let cards = [];
        for (let i of corps) {
            let config = mvc.config('mCard', i)
            if (config) {
                cards.push(config);
            }
        }

        // if(BrideWarHelper.isRoyalFlush(cards)){
        // id = 1;
        // }
        // else
        if (BrideWarHelper.isStraightFlush(cards)) {
            id = 1;
        }
        else if (BrideWarHelper.isFourOfAKind(cards)) {
            id = 2;
        }
        else if (BrideWarHelper.isFullHouse(cards)) {
            id = 3;
        }
        else if (BrideWarHelper.isFlush(cards)) {
            id = 4;
        }
        else if (BrideWarHelper.isContinuous(cards)) {
            id = 5;
        }
        else if (BrideWarHelper.isThreeOfAKind(cards)) {
            id = 6;
        }
        else if (BrideWarHelper.isTwoPairs(cards)) {
            id = 7;
        }
        else if (BrideWarHelper.isOnePair(cards)) {
            id = 8;
        }
        let poweruprow = mvc.config('mPowerup', id);
        if (!poweruprow) {
            return 10000
        }
        return 10000 + poweruprow.rate;
    },
    //是否为皇家同花顺
    isRoyalFlush(pais) {
        let isc = BrideWarHelper.isFlush(pais);
        if (!isc) {
            return false;
        }
        for (let i = 0; i < pais.length - 1; i++) {
            if (pais[i].sort < 10) {
                return false;
            }
        }
        return true
    },
    //是否为同花顺
    isStraightFlush(pais) {
        let isc = BrideWarHelper.isContinuous(pais);
        if (!isc) {
            return false;
        }
        for (let i = 0; i < pais.length - 1; i++) {
            if (pais[i].race != pais[i + 1].race) {
                return false;
            }
        }
        return true
    },
    //是否为顺子
    isContinuous(pais) {
        let numbers = [];
        for (let i = 0; i < pais.length; i++) {
            numbers.push(pais[i].sort);
        }
        if (BrideWarHelper.isNumberContinuous(numbers)) {
            return true;
        }
        else {
            for (let i = 0; i < numbers.length; i++) {
                if (numbers[i] == 14) {
                    numbers[i] = 1;
                }
            }
            if (BrideWarHelper.isNumberContinuous(numbers)) {
                return true;
            }
        }
        return false;
    },
    isNumberContinuous(numbers) {
        if (numbers == null || numbers.length < 5) {
            return false;
        }
        let jokers = 0;
        let list = [];
        for (let i = 0; i < numbers.length; i++) {
            if (numbers[i] == 0) {
                jokers++;
            } else {
                list.push(numbers[i]);
            }
        }
        if (jokers > 1) {
            return false;
        }
        BrideWarHelper.sorLst(list);
        if (list[0] - list[list.length - 1] > 4) {
            return false;
        }
        for (let i = 0; i < list.length - 1; i++) {
            if (list[i] == list[i + 1]) {
                return false;
            }
        }
        return true;
    },
    //是否为四条
    isFourOfAKind(pais) {
        let dic = {}
        for (let i of pais) {
            if (dic[i.num]) {
                dic[i.num] += 1;
            } else {
                dic[i.num] = 1;
            }
        }
        let hasFour = false;
        for (let key in dic) {
            let num = dic[key];
            if (num == 4) {
                hasFour = true;
            }
        }
        return hasFour;
    },
    //是否为满堂彩
    isFullHouse(pais) {
        let dic = {};
        for (let i of pais) {
            if (dic[i.num]) {
                dic[i.num] += 1;
            } else {
                dic[i.num] = 1;
            }
        }
        let hasThree = false;
        let hasTwo = false;
        for (let key in dic) {
            let num = dic[key];
            if (num == 3) {
                hasThree = true;
            }
            if (num == 2) {
                hasTwo = true;
            }
        }
        return hasThree && hasTwo;
    },
    //是否为同花
    isFlush(pais) {
        for (let i = 0; i < pais.length - 1; i++) {
            if (pais[i].race != pais[i + 1].race) {
                return false;
            }
        }
        return true;
    },
    //是否为三条
    isThreeOfAKind(pais) {
        let dic = {};
        for (let i of pais) {
            if (dic[i.num]) {
                dic[i.num] += 1;
            } else {
                dic[i.num] = 1;
            }
        }
        let hasThree = false;
        for (let key in dic) {
            let num = dic[key];
            if (num == 3) {
                hasThree = true;
            }
        }
        return hasThree;
    },
    //是否为两对
    isTwoPairs(pais) {
        let dic = {};
        for (let i of pais) {
            if (dic[i.num]) {
                dic[i.num] += 1;
            } else {
                dic[i.num] = 1;
            }
        }
        let hasTwo1 = false;
        let hasTwo2 = false;
        for (let key in dic) {
            let num = dic[key];
            if (num == 2) {
                if (hasTwo1) {
                    hasTwo2 = true;
                }
                else {
                    hasTwo1 = true;
                }
            }
        }
        return hasTwo1 && hasTwo2;
    },
    //是否为一对
    isOnePair(pais) {
        let dic = {};
        for (let i of pais) {
            if (dic[i.num]) {
                dic[i.num] += 1;
            } else {
                dic[i.num] = 1;
            }
        }
        let hasTwo = false;
        for (let key in dic) {
            let num = dic[key];
            if (num == 2) {
                hasTwo = true;
            }
        }
        return hasTwo;
    },

    sorLst(lst) {
        lst = lst.sort((n1, n2) => {
            if (n1 > n2) {
                return -1;
            }
            else if (n1 < n2) {
                return 1
            }
            else {
                return 1;
            }
        });
        return lst
    },

}
